package com.zsg.webview.Activities;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zsg.webview.Adapter.CommantAdapter;
import com.zsg.webview.Adapter.GridAdapter;
import com.zsg.webview.Config;
import com.zsg.webview.R;
import com.zsg.webview.ResponseJson.CommentResponse;
import com.zsg.webview.Util.Net;
import com.zsg.webview.Util.Tools;
import com.zsg.webview.WeiBoBaseClass.Status;

import org.json.JSONObject;

import java.util.ArrayList;

public class AboutActivity extends AppCompatActivity implements Config {
    View view;      //内容视图
    ScrollView scrollView;      //滑动布局的实例

    Status status;
    float density;  //像素密度

    String access_token;
    String commentUrl;      //获取评论信息的url;

    CommantAdapter adapter;

    MyLinearLayout commentLayout;       //评论布局
    RequestQueue requestQueue;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);

        commentLayout = (MyLinearLayout) findViewById(R.id.mylinearLayout);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        scrollView.setOnTouchListener(listener);
        requestQueue = Net.getInstance(getApplicationContext()).getRequestQueue();
        getDensity();
        readAccessTaken();

        status = (Status) getIntent().getSerializableExtra("status");
        initContentView();     //初始化内容视图
        initCommentView();      //初始化评论视图

    }

    private void initContentView() {
        //根据 status中 多图数组的数量 来判断 微博类型
        if (status.pic_urls.size() == 0) {
            //文本
            view = getLayoutInflater().inflate(R.layout.item_string2, null);
        } else if (status.pic_urls.size() == 1) {
            // 单张图片
            view = getLayoutInflater().inflate(R.layout.item_image2, null);
            //显示大图
            ImageView image = (ImageView) view.findViewById(R.id.imagepic);
            Picasso.with(this).load(status.original_pic)
                    .placeholder(R.drawable.loadwait)
                    .error(R.drawable.error)
                    .into(image);
        } else {
            //多张图片
            view = getLayoutInflater().inflate(R.layout.item_imagearr2, null);
            GridView gridview = (GridView) view.findViewById(R.id.imagearr);
            gridview.setEnabled(false);

            ArrayList<Status.PicURLS> urls = status.pic_urls;
            GridAdapter gridAdapter = new GridAdapter(this, urls, GridAdapter.BM_PIC);

            //设置gridview的高度 不然显示不出完整数据

            ViewGroup.LayoutParams params = gridview.getLayoutParams();
            params.width = (int) (333 * density);
            if (urls.size() <= 3) {
                params.height = (int) (110 * density);
            } else if (urls.size() > 3 && urls.size() < 7) {
                params.height = (int) (220 * density);
            } else if (urls.size() >= 7) {
                params.height = (int) (330 * density);
            }

            gridview.setLayoutParams(params);
            gridview.setAdapter(gridAdapter);

        }

        TextView name = (TextView) view.findViewById(R.id.name);
        TextView message = (TextView) view.findViewById(R.id.message);
        TextView about = (TextView) view.findViewById(R.id.about);
        ImageView icon = (ImageView) view.findViewById(R.id.imageicon);
        name.setText(status.user.screen_name);

        message.setText(Tools.changeTextToFace(this,
                Html.fromHtml(Tools.atBlue(status.text))));
        about.setText("来自 " + status.getSource());
        //加载头像
        Picasso.with(this)
                .load(status.user.profile_image_url)
                .into(icon);

        //将内容view放入布局中
        LinearLayout lin = (LinearLayout) findViewById(R.id.linerlayout);
        lin.addView(view);
    }


    private void initCommentView() {
        ((TextView) findViewById(R.id.retweetcount)).setText(status.reposts_count + "");
        ((TextView) findViewById(R.id.commentcount)).setText(status.comments_count + "");
        ((TextView) findViewById(R.id.praisecount)).setText(status.attitudes_count + "");
        adapter = new CommantAdapter(this);
        adapter.registerLayout(commentLayout);
        LoadComment(1,TYPE_REFRESH);
    }

    //加载评论内容
    private void LoadComment(int page, final int type) {
        initUrl(page);
        JsonObjectRequest request = new JsonObjectRequest(
                commentUrl,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(MainActivity.TAG, response.toString());
                        Gson gson = new Gson();
                        CommentResponse commentResponse = gson.fromJson(response.toString(), CommentResponse.class);
                        Log.d(MainActivity.TAG, commentResponse.comments.toString());
                        adapter.updateData(commentResponse.comments,type);
                        adapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (requestQueue.getCache().get(commentUrl) != null) {
                            //通过url的到缓存的数据
                            byte[] data = requestQueue.getCache().get(commentUrl).data;
                            Gson gson = new Gson();
                            CommentResponse commentResponse = gson.fromJson(new String(data), CommentResponse.class);
                            Log.d(MainActivity.TAG, commentResponse.comments.toString());
                            adapter.updateData(commentResponse.comments, type);
                            adapter.notifyDataSetChanged();

                        }
                    }
                }
        );

        requestQueue.add(request);
    }

    public void initUrl(int page) {
        commentUrl = "https://api.weibo.com/2/comments/show.json?" +
                "access_token=" + access_token +
                "&id=" + status.id +
                "&count=" + pagecount +
                "&page=" + page;
    }


    private void getDensity() {
        //获得屏幕dpi 像素密度
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        density = metric.density;  // 密度（0.75 / 1.0 / 1.5）
        // int densityDpi = metric.densityDpi;  // 密度DPI（120 / 160 / 240）
    }


    /**
     * 获取保存在磁盘中的AccessTaken
     */
    private void readAccessTaken() {

        SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        // 使用getString方法获得value，注意第2个参数是value的默认值
        access_token = sharedPreferences.getString(TAKEN, "");
        //Log.d(MainActivity.TAG,"access_token: "+access_token);


    }

    /**
     * 监听 ScrollView 滑动 判断是否滑动到最低端  然后执行评论加载下一页
     */
    View.OnTouchListener listener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {

                case MotionEvent.ACTION_UP:
                    //ScrollView组件只允许一个子View,获取子View的高度即所要的ScrollView的整体高度
                    View childView = scrollView.getChildAt(0);
                    //getMeasuredHeight()返回的是原始测量高度，与屏幕无关，getHeight()返回的是在屏幕上显示的高度
                    Log.d(MainActivity.TAG,"childView.getMeasuredHeight()="+childView.getMeasuredHeight()+"  getScrollY()="+scrollView.getScrollY()+"  height="+scrollView.getHeight());
                    if (scrollView != null && scrollView.getScrollY() + scrollView.getHeight()>=childView.getMeasuredHeight()) {
                        View lastview=commentLayout.getChildAt(adapter.getCount()-1);
                        TextView textView = (TextView) lastview.findViewById(R.id.textView);
                        textView.setText("加载中...");
                        lastview.findViewById(R.id.imageView).setVisibility(View.VISIBLE);

                        Toast.makeText(AboutActivity.this,"滑动到了最底端",Toast.LENGTH_SHORT).show();
                        LoadComment(adapter.data.size()/pagecount+1,TYPE_GETMORE);
                    }
                    break;
            }
            return false;

        }
    };


}
